package com.biscuit.page.basicservice.service;

import com.biscuit.page.basicservice.api.model.request.file.FileImageUploadAReq;
import com.biscuit.page.basicservice.api.model.response.file.FileImageUploadAResp;
import com.biscuit.page.basicservice.bean.FileMinioClient;
import com.biscuit.page.basicservice.model.enums.FileWorkTypePrefixEnum;
import com.biscuit.page.basicservice.model.exception.BaseException;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

/**
 * @author mazihao
 * @createTime 2024/4/1 9:31
 */
@Slf4j
@Service
public class FileService {

    @Resource
    private FileMinioClient fileMinioClient;

    public FileImageUploadAResp imageUpload(MultipartFile multipartFile, FileImageUploadAReq req) {
        try {
            // 获取上传图片名称
            String originalFilename = multipartFile.getOriginalFilename();

            // 获取文件输入流
            InputStream inputStream = multipartFile.getInputStream();

            // 获取文件类型
            String contentType = multipartFile.getContentType();

            // 根据业务类型获取文件前缀
            FileWorkTypePrefixEnum prefixEnum = FileWorkTypePrefixEnum.getTypeEnumByType(req.getWorkType());

            // 数据校验
            BaseExceptionUtil.throwException(Objects.nonNull(prefixEnum), "业务类型填写错误");
            BaseExceptionUtil.throwException(StringUtils.isNotBlank(originalFilename), "文件名称为空");
            BaseExceptionUtil.throwException(
                    Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "tiff", "svg", "webp").contains(originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase()),
                    "图片类型不正常"
            );
            BaseExceptionUtil.throwException(!multipartFile.isEmpty(), ":文件为空");

            // 生成新的文件名称
            String fileName = CommonUtil.getUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

            // 上传图片
            String path = this.fileMinioClient.upload(fileName, prefixEnum.getPrefix(), inputStream, contentType);

            // 返回成功信息
            FileImageUploadAResp response = new FileImageUploadAResp();
            response.setFileName(fileName);
            response.setPath(path);
            return response;
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }
}
